package com.framework.auth.util;

import com.framework.auth.constants.Auth2Constant;
import com.framework.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: token安全检测工具类
 */
@Slf4j
public class SecurityUtil {
    public static String BEARER = "bearer";
    public static Integer AUTH_LENGTH = 7;
    /**
     * 从HttpServletRequest里获取token
     *
     * @param request HttpServletRequest
     * @return token
     */
    public static String getHeaderToken(HttpServletRequest request) {
        return request.getHeader(Auth2Constant.HEADER_TOKEN);
    }

    /**
     * 从HttpServletRequest里获取token
     *
     * @param request HttpServletRequest
     * @return token
     */
    public static String getToken(HttpServletRequest request) {
        String headerToken = getHeaderToken(request);
        if (StringUtils.isEmpty(headerToken)) {
            throw new BusinessException("没有携带Token信息！");
        }
        return StringUtils.isNotEmpty(headerToken) ? getToken(headerToken) : "";
    }

    /**
     * 获取token串
     *
     * @param auth token
     * @return String
     */
    public static String getToken(String auth) {
        if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
            String headStr = auth.substring(0, 6).toLowerCase();
            if (headStr.compareTo(BEARER) == 0) {
                auth = auth.substring(7);
            }
            return auth;
        }
        return null;
    }
}
